package com.bennu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bennu.common.R;

import com.bennu.domain.User;
import com.bennu.service.UserService;
import com.bennu.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    //redis接口
    @Autowired
    private RedisTemplate redisTemplate;
    //邮件接口
    @Autowired
    private JavaMailSender mailSender;
    //手机验证码获取方法
    /*@PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if ( StringUtils.isNotEmpty( phone ) ){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode( 6 ).toString();
            //调用短信api完成发送短信
            log.info( "验证码为{}",code );
           // SMSUtils.sendMessage( "瑞吉外卖","",phone,code );

            //生成的验证码保存session
            //session.setAttribute( phone,code );

            //将生成的验证码缓存到redis，设置时间五分钟
            redisTemplate.opsForValue().set( phone,code,5, TimeUnit.MINUTES );
            return R.success( "手机验证码发送成功" );
        }

        return R.error( "验证码发送失败" );
    }*/
    //邮箱验证码获取方法
    //	获得发件人信息
    @Value("${spring.mail.username}")
    private String from;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,  HttpSession session){
        //创建邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);

        message.setTo( user.getEmail());
        String email = user.getEmail();
            if ( StringUtils.isNotEmpty( email ) ){
                message.setSubject("尊敬的用户您本次的验证码为");
                //生成验证码
                String code = ValidateCodeUtils.generateValidateCode( 6 ).toString();
                //调用短信api完成发送短信
                log.info( "验证码为{}",code );
                message.setText("尊敬的VIP用户,您好:\n"
                                + "\n本次请求的邮件验证码为:" + code + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）");
                mailSender.send(message);
                //将生成的验证码缓存到redis，设置时间五分钟
                redisTemplate.opsForValue().set( email,code,5, TimeUnit.MINUTES );
                return R.success( "邮箱验证码发送成功" );

        }
       /*User user = QcbyContext.getUser(request.getHeader("token"));
            user.setVerCode(verCode);
            return ResultJson.ok("发送成功");*/
        return R.error( "验证码发送失败" );


    }
    //移动端用户登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info( map.toString() );
        //获取手机号
        String email = map.get( "email").toString();

        //获取验证码
        String code = map.get( "code" ).toString();
        //从session中获取保存的验证码
        //Object codeInSession = session.getAttribute( phone );
        //在redis中获取验证码
        Object codeInSession =redisTemplate.opsForValue().get( email );
        //进行验证码比对
        if ( codeInSession!=null&&codeInSession.equals( code ) ){
            //比对成功，登录成功
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq( User::getEmail,email );
            //判断当前手机号是否为新用户，如果是新用户自动完成注册
            User user = userService.getOne( queryWrapper );
            if ( user==null ){
                 user = new User();
                user.setEmail( email );
                user.setStatus( 1 );
                userService.save( user );
            }
            session.setAttribute( "user",user.getId() );
            //登录成功
            redisTemplate.delete( email );
            return R.success( user );
        }

        return R.error( "登录失败" );
    }
    //用户退出登录
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        //清理session中保存的员工数据
        request.getSession().removeAttribute( "employee");
        return R.success( "退出成功" );
    }

}
